package com.gr.dmbackend.service.Impl.dormaddmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.DormaddminMapper;
import com.gr.dmbackend.mapper.EventMapper;
import com.gr.dmbackend.mapper.StudentEventMapper;
import com.gr.dmbackend.model.Event;
import com.gr.dmbackend.model.StudentEvent;
import com.gr.dmbackend.service.dormaddmin.DeleteEventService;
import com.gr.dmbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeleteEventServiceImpl implements DeleteEventService {

    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private StudentEventMapper studentEventMapper;

    @Override
    public JSONObject deleteEvent(int id) {

        JSONObject resp = new JSONObject();

        Event event = eventMapper.selectById(id);
        if (event == null) {
            resp.put("error_message", "当前通知不存在");
            return resp;
        }
        if (!GetUserUtil.getCurrentUser().getUsername().equals(event.getWorkId())) {
            resp.put("error_message", "error");
            return resp;
        }

        QueryWrapper<StudentEvent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("event_id", id);
        List<StudentEvent> studentEvents = studentEventMapper.selectList(queryWrapper);
        for (StudentEvent studentEvent: studentEvents) {
            studentEventMapper.deleteById(studentEvent);
        }
        eventMapper.deleteById(id);
        resp.put("error_message", "success");

        return resp;
    }
}
